package com.wkc;


import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.wkc.adapter.ItemListAdapter;
import com.wkc.data.ListItem;
import com.wkc.R;
import wwk.common.constant.Commonstant;
import wwk.common.http.HttpEngine;
import wwk.common.http.HttpResponseData;
import wwk.common.http.HttpResponseInterface;
import wwk.common.json.JSONArray;
import wwk.common.json.JSONObject;
import wwk.common.util.FileUtil;
import wwk.common.util.JsonUtil;
import wwk.common.util.LayoutUtil;
import wwk.common.widget.LoadMoreView;
import wwk.common.widget.NavigationBar;
import wwk.common.widget.OnLoadMoreListener;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

/*
 * {"id":148,"title":"","videoUrl":"/uploads2/media /8FMEKtjQa7sc6Ig.mp4",
 * "datetime":"2013-08-09","duration":"δ ֪",
 * "thumbnailUrl":"/uploads2/media/8FMEKtjQa7sc6Ig.jpg"}
 * 
 * {"id":138,"title":"","videoUrl":"/uploads2/media /x8HO1ofGFhUZWnD.mp4",
 * "datetime":"2013-08-03",
 * "duration":"δ ֪","thumbnailUrl":"/uploads2/allimg/DB8TxH4XgUNwUWI.png"}
 * */

public class ItemListActivity extends Activity implements OnItemClickListener,
HttpResponseInterface, OnLoadMoreListener, OnRefreshListener2<ListView>
{	
	private ItemListAdapter listViewAdapter;
	private ListView listView;
	private HttpEngine httpEngine;
	private PullToRefreshListView pullToRefreshListView;
	//private LoadMoreView loadMoreView;
	private int topItemId=0;
	private int lastItemId=0;
	private long lastBackPressedTime = 0;
	private Toast toast=null;
	
	/*
	//private static final String server="192.168.0.103";
	//private static final String server="192.168.65.72";
	private static final String RefreshUrlFormat="http://192.168.65.72/reading/controller/getItemList.php?categoryCode=0&topItemId=%d";
	private static final String GetMoreUrlFormat="http://192.168.65.72/reading/controller/getItemList.php?categoryCode=0&lastItemId=%d";
	private static final String dataKey="data";
	*/
	
	private static final String RefreshUrlFormat="http://weike.zbedu.net/mobile/getList.php?topId=%d";
	private static final String GetMoreUrlFormat="http://weike.zbedu.net/mobile/getList.php?lastId=%d";
	private static final String dataKey="dataarray";
	
	private static final String RequestServer="http://weike.zbedu.net";
	
	private Handler handler=new Handler() 
	{
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			
			switch(msg.what)
			{
				case 0:
					{
						listViewAdapter.notifyDataSetChanged();
						
						if(msg.arg1==0)
						{
							pullToRefreshListView.onRefreshComplete();
							
							if(msg.arg2>0)
							{
								String format=ItemListActivity.this.getString(R.string.updateResultFormat);
								String str=String.format(format, msg.arg2);
								Toast toast=Toast.makeText(ItemListActivity.this, str, Toast.LENGTH_SHORT);
								toast.setGravity(Gravity.CENTER,0,0); 
								toast.show();
							}
						}
						else
						{
							pullToRefreshListView.onRefreshComplete();
							//loadMoreView.onLoadComplete();
						}
						
						TextView textView=(TextView)findViewById(android.R.id.empty);
						if(listViewAdapter.getCount()==0)
						{
							textView.setText(R.string.weiKeChengEmpty);
						}
					}
					break;
			}
		}
	};
	
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        
		setContentView(R.layout.item_list_activity);
		
		NavigationBar navigationBar=(NavigationBar)this.findViewById(R.id.navBar);
        setTitle(R.string.weiKeCheng);
        navigationBar.setTitle(this.getTitle().toString());
        
        pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);

		// Set a listener to be invoked when the list should be refreshed.
        pullToRefreshListView.setOnRefreshListener(this);
        pullToRefreshListView.setOnRefreshListener(this);

		// Add an end-of-list listener
        pullToRefreshListView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() 
        {
			@Override
			public void onLastItemVisible() 
			{
				//Toast.makeText(ItemListActivity.this, "End of List!", Toast.LENGTH_SHORT).show();
			}
		});

        listView = pullToRefreshListView.getRefreshableView();
        
        /*
        loadMoreView=(LoadMoreView)findViewById(R.id.loadMore);
		if(loadMoreView!=null)
		{
			ViewGroup parent=(ViewGroup)loadMoreView.getParent();
			parent.removeView(loadMoreView);
			
			ViewGroup.LayoutParams lp=loadMoreView.getLayoutParams();
			lp=new AbsListView.LayoutParams(lp.width,lp.height);
			loadMoreView.setLayoutParams(lp);
			
			listView.addFooterView(loadMoreView);
			
			loadMoreView.setOnLoadMoreListener(this);
		}
		*/
		
		/*
		LoadMoreView lv=new LoadMoreView(this);
		AbsListView.LayoutParams lp=new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,80);
		lv.setLayoutParams(lp);
		listView.addFooterView(lv);
		*/
		
		//registerForContextMenu(listView);  

		//adapter
		listViewAdapter=new ItemListAdapter(this);
		listView.setAdapter(listViewAdapter);
		
		//listener
		listView.setOnItemClickListener(this);
		
		//empty view
		View emptyView=findViewById(android.R.id.empty);
		listView.setEmptyView(emptyView); 
		
		
		//请求网络数据
		onPullDownToRefresh(pullToRefreshListView);
		TextView textView=(TextView)findViewById(android.R.id.empty);
		textView.setText(R.string.loadingList);
		
		
		/*
		//加载测试数据
		String jsonString=FileUtil.getStringFromAssets(this, "test.txt", "utf-8");
		processListItemJsonString(jsonString,0);
		*/
    }
  
    public void onStart()
	{
		super.onStart();
	}
	
	public void onPause()
	{
		super.onPause();
	}
	
	public void onResume()
	{
		super.onResume();
	}
	
	public void onStop()
	{
		super.onStop();
	}
	
	public void onDestroy()
	{
		super.onDestroy();
		
		if(httpEngine!=null)
		{
			httpEngine.httpResponseInterface=null;
			httpEngine.cancel();
			httpEngine=null;
		}
	}
	
	@Override
	public void onBackPressed() 
	{
		Log.i("NavigationActivity onBackPressed()","");
		
		long theTime=System.currentTimeMillis();
		if(theTime-lastBackPressedTime<=2000)
		{
			toast.cancel();
			super.onBackPressed();
		}
		else
		{
			lastBackPressedTime=theTime;
			toast=Toast.makeText(this,this.getString(R.string.twiceExit), Toast.LENGTH_SHORT);
			toast.show();
		}
	}
    
    @Override
	protected void onActivityResult(int requestCode, int resultCode,Intent data) 
	{
    }
	
	public void onItemClick(AdapterView<?> parent, View view, int position,long id) 
	{
        String path = "http://forum.ea3w.com/coll_ea3w/attach/2008_10/12237832415.3gp";
        //path = "http://www.androidbook.com/akc/filestorage/android/documentfiles/3389/movie.mp4";
        //path = "http://video19.ifeng.com/video07/2013/08/26/36723-102-055-1208.mp4";
        //path = "http://data.vod.itc.cn/?new=/136/121/lUQsGLAlMbvKE0ZWIEtU1.mp4";
        
        String title="";

        ListItem item=(ListItem)parent.getAdapter().getItem(position);
        path=item.videoUrl;
        title=item.title;
        
        if(path==null || path.length()==0)
        {
        		return;
        }
        
        Log.i(title,path);
        
        //String content=String.format("<video src=\"%s\"></video>",path);
		//Intent intent = new Intent(this, WebViewActivity.class);
		//intent.putExtra("content",content);
		
		Intent intent = new Intent(this, MediaPlayerActivity.class);
		//Intent intent = new Intent(this, VideoViewActivity.class);
		intent.putExtra("videoUrl", path);
		intent.putExtra("title",title);
        startActivity(intent);
	}

	@Override
	public void onHttpResponsed(HttpResponseData httpResponseData)
	{
		httpEngine=null;
		

		String jsonString=null;
		
		if(httpResponseData.bytes!=null)
		{
			try 
			{
				String encoding=Commonstant.ENCODING_UTF8;
				encoding="gb2312";
				encoding=httpResponseData.encoding;
				
				jsonString = new String(httpResponseData.bytes,
						0, httpResponseData.getBytesSize(),encoding);//Commonstant.ENCODING_UTF8
			} 
			catch (Exception e) 
			{
				e.printStackTrace();
			}
		}
		
		processListItemJsonString(jsonString,httpResponseData.tag);
	}
	
	private void processListItemJsonString(String jsonString,int tag)
	{
		Log.i("response",jsonString);
		
		if(jsonString==null)
		{
			return;
		}
		
		JSONObject jsonObject=JsonUtil.createJsonObject(jsonString);
		JSONArray dataArray=JsonUtil.getJsonArray(jsonObject, dataKey);//dataarray

		int length=0;

		if(dataArray!=null && dataArray.length()>0)
		{
			length=dataArray.length();
			
			if(tag==0)
			{
				//refresh
				
				//for(int i=length-1;i>=0;i--)//desc
				for(int i=0;i<length;i++)//asc
				{
					JSONObject jsonListItem=JsonUtil.getJsonObject(dataArray, i);
					
					ListItem listItem=new ListItem();
					listItem.parse(jsonListItem, RequestServer);
							
					listViewAdapter.insertListItem(listItem);
				}
			}
			else
			{
				//loadmore
				
				for(int i=0;i<length;i++)
				//for(int i=length-1;i>=0;i--)
				{
					JSONObject jsonListItem=JsonUtil.getJsonObject(dataArray, i);
					
					ListItem listItem=new ListItem();
					listItem.parse(jsonListItem, RequestServer);
					
					listViewAdapter.addListItem(listItem);
				}
			}
			
			topItemId=(int)listViewAdapter.getItemId(0);
			lastItemId=(int)listViewAdapter.getItemId(listViewAdapter.getCount()-1);
		}
		
		Message msg=new Message();
		msg.what=0;
		msg.arg1=tag;
		msg.arg2=length;
		handler.sendMessage(msg);
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView)
	{
//		String label = DateUtils.formatDateTime(getApplicationContext(), 
//				System.currentTimeMillis(),
//				DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE 
//				| DateUtils.FORMAT_ABBREV_ALL);
//
//		// Update the LastUpdatedLabel
//		refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

		String url=String.format(RefreshUrlFormat,topItemId);
		Log.i("request",url);
		
		if(httpEngine!=null)
		{
			httpEngine.cancel();
			httpEngine=null;
		}
		
		httpEngine=new HttpEngine(ItemListActivity.this);
		httpEngine.setUrl(url);
		httpEngine.tag=0;
		httpEngine.request();
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) 
	{
		onLoadMoreClicked();
	}
	
	@Override
	public void onLoadMoreClicked() 
	{
		String url=String.format(GetMoreUrlFormat,lastItemId);
		Log.i("request",url);
		
		if(httpEngine!=null)
		{
			httpEngine.cancel();
			httpEngine=null;
		}
		
		httpEngine=new HttpEngine(ItemListActivity.this);
		httpEngine.setUrl(url);
		httpEngine.tag=1;
		httpEngine.request();
	}
}
